//
//  DemandTheHallViewController.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/9.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "DemandTheHallViewController.h"
#import "DemandHeaderView.h"
#import "DemandCollectionCell.h"
#import "ReleaseModel.h"
#import "DemandTheHallContentVC.h"
#import "ShowView.h"
#import "DemandAndServiceSearchView.h"
#import "NearHistoryView.h"
#import "HomeModel.h"
#import "DemandAndServiceSearchTabVC.h"
@interface DemandTheHallViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,DemandHeaderViewDelegate,DemandCollectionCellDelegate,NearHistoryViewDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) NSMutableArray *titles;
@property(nonatomic,strong) NSMutableArray *subTitles;
@property(nonatomic,strong) UICollectionViewFlowLayout *flow;
@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) DemandHeaderView *headerView;
@property(nonatomic,strong) ReleaseModel *model;
@property(nonatomic,assign) NSInteger fatherId;
@property(nonatomic,strong) ShowView *showView;
@property(nonatomic,strong) NearHistoryView *nearHisView;
@property(nonatomic,strong) NSMutableArray *historyMuta;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) Reachability *reach;
@end
static NSString *identifier = @"cell";
@implementation DemandTheHallViewController
-(NSMutableArray *)historyMuta
{
    if (!_historyMuta) {
        NSArray *pathFile = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *homeSearchPreference = [pathFile[0] stringByAppendingPathComponent:@"demandThehallHistory.plist"];
        NSArray *temp = [NSArray arrayWithContentsOfFile:homeSearchPreference];
        XLog(@"temp.count:%ld",temp.count);
        if (_historyMuta.count) {
            _historyMuta = [NSMutableArray arrayWithArray:temp];
        }else {
            _historyMuta = [NSMutableArray array];
        }
    }
    return _historyMuta;
}
-(NSMutableArray *)titles
{
    if (!_titles) {
        _titles = [NSMutableArray array];
    }
    return _titles;
}
-(NSMutableArray *)subTitles
{
    if (!_subTitles) {
        _subTitles = [NSMutableArray array];
    }
    return _subTitles;
}
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        self.flow = [[UICollectionViewFlowLayout alloc]init];
        self.flow.minimumLineSpacing = 0;
        self.flow.minimumInteritemSpacing = 0;
        self.flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.headerView.frame.size.height, kVWidth,  kVHeight-self.headerView.frame.size.height-kNavAndStatusHight-kTabBarHeight) collectionViewLayout:self.flow];
        _collectionView.backgroundColor = kBg;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhite;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.manager = [AFHTTPSessionManager manager];
    DemandAndServiceSearchView *searchView = [[DemandAndServiceSearchView alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.navigationBar.bounds.size.width, self.navigationController.navigationBar.bounds.size.height-8)];
    
    __weak typeof (self)weakSelf = self;
    searchView.returnValueBlock = ^(NSInteger selected) {
        if (selected == 0) {//历史记录
            XLog(@"returnValueBlock");
            self.nearHisView = [[NearHistoryView alloc]initWithFrame:CGRectMake(0, 0, kVWidth, kUIScreen.size.height)];
            self.nearHisView.index = 1;
            self.nearHisView.show = YES;
            self.nearHisView.delegate = self;
            [weakSelf.view.superview.window addSubview:self.nearHisView];

        }else {//搜索
            DemandAndServiceSearchTabVC *vc = [[DemandAndServiceSearchTabVC alloc]init];
            vc.searchIndex = 1;
            [self.headerView.showView hideListViewAnimation];
            [self.navigationController pushViewController:vc animated:YES];
            
        }
        XLog(@"selected:%ld",selected);
    };
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:searchView];
    self.model = [[ReleaseModel alloc]init];
    self.fatherId = 1;
    self.headerView = [[DemandHeaderView alloc]initWithFrame:CGRectMake(0, 0, kUIScreen.size.width, 80)];
    self.headerView.delegate = self;
    self.headerView.kNavHeight = kNavAndStatusHight;
    XLog(@"self.headerView.count%ld",self.headerView.titles.count);
    [self.view addSubview:self.headerView];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[DemandCollectionCell class] forCellWithReuseIdentifier:identifier];
    [self.view addSubview:self.collectionView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiulist:) name:@"qingqiulist" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiulistlistByFatherId:) name:@"qingqiulistlistByFatherId" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusibai:) name:@"qingqiusibai" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeInternet:) name:@"changeInternet" object:nil];
    [self reloadInternetData];
    
}
-(void)changeInternet:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"DemandCollectionCell:%@",dict);
    
    [self reloadInternetData];
    
}
#pragma mark-历史记录---跳转到详情
- (void)nearHistoryView:(NearHistoryView *)nearHistoryView withHidden:(BOOL)hidden withIndex:(NSInteger)index withHomeModel:(nonnull HomeModel *)homeModel
{
    DemandTheHallContentVC *vc = [[DemandTheHallContentVC alloc]init];
    vc.homeModel = homeModel;
    [nearHistoryView removeFromSuperview];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)nearHistoryView:(NearHistoryView *)nearHistoryView withHidden:(BOOL)hidden
{
    [nearHistoryView removeFromSuperview];
}
#pragma mark-代理:条件搜索---大类
-(void)reloadInternetData
{
    //    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    //    [WSProgressHUD show];
    NSDictionary *dict = nil;
    [CustomeManager POSTWithURLIndex:10 parameters:dict success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
    
}
-(void)qingqiulist:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    //    XLog(@"dict:%@",dict);
    NSArray *date = [dict objectForKey:@"date"];
    for (NSDictionary *dict in date) {
        self.model = [ReleaseModel mj_objectWithKeyValues:dict];
        [self.titles addObject:self.model];
    };
   
    XLog(@"self.titles:%ld",self.titles.count);
    self.headerView.titles = self.titles;
    [self.collectionView reloadData];
    [self reloadInternetSubData];
}

-(void)qingqiusibai:(NSNotification *)info
{
    self.collectionView.emptyDataSetSource = self;
    self.collectionView.emptyDataSetDelegate = self;
     [self.collectionView reloadData];
    XLog(@"DemandTheHallViewControllerqingqiusibai");
}

#pragma mark-代理:条件搜索---小类
-(void)reloadInternetSubData{
    NSString *fatherId = [NSString stringWithFormat:@"%ld",self.fatherId];
    NSDictionary *dictFather = @{
                                 @"fatherId":fatherId
                                 };
    XLog(@"fatherId:%@",fatherId);
    [CustomeManager POSTWithURLIndex:11 parameters:dictFather success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)qingqiulistlistByFatherId:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    //    XLog(@"dict:%@",dict);
    NSArray *date = [dict objectForKey:@"date"];
    for (NSDictionary *dict in date) {
        self.model = [ReleaseModel mj_objectWithKeyValues:dict];
        [self.subTitles addObject:self.model];
        
    }
    
    self.model = self.subTitles[0];
    NSMutableDictionary *dictTitle = [NSMutableDictionary dictionary];
    [dictTitle setValue:@"全部" forKey:@"content"];
    ReleaseModel *model = [ReleaseModel mj_objectWithKeyValues:dictTitle];
    [self.subTitles insertObject:model atIndex:0];
    self.headerView.subTitles = self.subTitles;
//    MCButton *mcBtn = (MCButton *)[self.headerView.titleScrollView viewWithTag:self.fatherId];
//    [self.headerView clickBtn:mcBtn];
    
}
#pragma mark-点击大类
-(void)demandHeaderView:(DemandHeaderView *)demandHeaderView withTitleBtn:(MCButton *)mcBtn withSubDefaultTag:(NSInteger)subTag
{
    XLog(@"mcBtn:%@---%ld",[mcBtn currentTitle],subTag);
//        [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
//        [WSProgressHUD show];
    self.subTitles = nil;
    self.fatherId = mcBtn.tag;
    [self reloadInternetSubData];
    [self.collectionView setContentOffset:CGPointMake((mcBtn.tag-1)*kVWidth, 0) animated:NO];
    
}
#pragma mark-点击:小类
- (void)demandHeaderView:(DemandHeaderView *)demandHeaderView withTitleBtn:(MCButton *)mcBtn withSubBtn:(UIButton *)subBtn WithSubModel:(nonnull ReleaseModel *)subModel
{
//    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
//    [WSProgressHUD show];
    XLog(@"mcBtn:%@---%@",[mcBtn currentTitle],[subBtn currentTitle]);
    XLog(@"%@",subModel.content);
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:mcBtn.tag-1 inSection:0];
    DemandCollectionCell *cell = (DemandCollectionCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    cell.releaseSubModel = subModel;

}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x/kVWidth;
    MCButton *mcBtn = (MCButton *)[self.headerView.titleScrollView viewWithTag:index+1];
    [self.headerView clickBtn:mcBtn];
    
    XLog(@"index:%ld",index);
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.titles.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DemandCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    self.indexPath = indexPath;
    cell.delegate = self;
    ReleaseModel *model = self.titles[indexPath.row];
    cell.releaseModel = model;
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kVWidth, kVHeight);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
//    if (section == 0) {
        return CGSizeMake(0, 0);
//    }else {
//        return CGSizeMake(200, 0);
//    }
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
//    if(section == 1){
//        return UIEdgeInsetsMake(0, 0, 0.5, 0);//分别为上、左、下、右
//    }else{
        return UIEdgeInsetsMake(0, 0, 0, 0);//分别为上、左、下、右
//    }
    
}
#pragma mark-代理:刷新搜藏按钮
- (void)demandCollectionCell:(DemandCollectionCell *)demandCollectionCell withCollectReload:(BOOL)collectReload
{
    
}
#pragma mark-代理:跳转需求详情
-(void)demandCollectionCell:(DemandCollectionCell *)demandCollectionCell withModel:(HomeModel *)model withIndexPath:(nonnull NSIndexPath *)indexPath
{
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"token":[UserDefaultsHelper readToken],
                  @"dids":[NumberSwitchString numberSwitchString:model.id]
                  };
    XLog(@"历史需求self.dict:%@",self.dict);
    self.urlString = [NSString stringWithFormat:@"%@/history/insertDemand",kUrl];
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XLog(@"error:%@",error);
    }];
    DemandTheHallContentVC *vc = [[DemandTheHallContentVC alloc]init];
    vc.returnValueBlock = ^(NSInteger selected) {
        model.collectStatus = selected;
        [demandCollectionCell.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    };
    vc.homeModel = model;
    [self.navigationController pushViewController:vc animated:YES];
}
//#pragma mark-代理:添加需求历史记录
//-(void)historyinsertDemand:(NSNotification *)info
//{
//    NSDictionary *dict = info.userInfo;
//    XLog(@"历史需求dict:%@",dict);
//}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"nonetwork"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"请在iPhone的设置-无线局域网中允许商集使用WLAN与蜂窝移动网的应用";
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    // 设置所有字体大小为 #15
    [attStr addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:15.0]
                   range:NSMakeRange(0, text.length)];
    // 设置所有字体颜色为浅灰色
    [attStr addAttribute:NSForegroundColorAttributeName
                   value:[UIColor lightGrayColor]
                   range:NSMakeRange(0, text.length)];
    // 设置指定4个字体为蓝色
    [attStr addAttribute:NSForegroundColorAttributeName
                   value:[UIColor colorWithRed:47/255.0 green:119/255.0 blue:246/255.0 alpha:1]
                   range:NSMakeRange(9, 2)];
    [attStr addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:18.0]
                   range:NSMakeRange(9, 2)];
    return attStr;
}
- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView
{
    //    [self reloadInternet];
    NSString * urlString = UIApplicationOpenSettingsURLString;
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
        if ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            }
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }
    }
}

@end
